/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-07 16:08:42
 * @LastEditTime: 2023-12-14 17:01:31
 */
import { defineComponent, ref, withModifiers } from 'vue'
import { _, ikArray } from 'iking-utils'
import type { Ref } from 'vue'
import IkPageFull from '@g/components/LayoutCom/IkPageFull/index.vue'
import IkPageTabs from '@g/components/LayoutCom/IkPageFull/IkPageTabs.vue'
import IkSplitPan from '@g/components/LayoutCom/IkSplitPan/index.vue'
import IkItemList from '@g/components/BaseCom/IkItemList/index.vue'
import IkSideText from '@g/components/BaseCom/IkTableCellCom/IkSideText.vue'
import IkBtnContent from '@g/components/BaseCom/IkBtnContent/index'
import RoleModal from './RoleEditModal.vue'
import RoleListComfig from './RoleListConfig'
import IkSvgIcon from '@/global/components/BaseCom/IkSvgIcon/index.vue'
import { roleApi, roleUserApi } from '@/MainApp/apis/role'
import type { RoleFormState } from '@/global/enums/role'
import {IkingPicker} from 'iking-web-ui'
import {ElPopconfirm} from 'element-plus'


import './index.scss'

const roleManage = defineComponent({
  components: {
    RoleListComfig,
    RoleModal
  },
  setup() {
    const { msgWarning, msgSuccess, msgBoxWarnAsync } = useMessage()

    const loading = ref(false)

    const visible = ref(false)
    const editData: Ref<RoleFormState | null> = ref(null)
    const refRole = ref()
    const helpState = ref(false)
    const selectId: Ref<RoleFormState | null> = ref(null)

    const roleLists: Ref<
      Array<
        RoleFormState & {
          label?: string
          value?: any
        }
      >
    > = ref([])
    const __roleLists: Ref<Array<RoleFormState>> = ref([])
    // let recordList: Array<RoleFormState> = []
    // 过滤
    // const searchText = ref('')
    const selectIdName = ref('')

    /** v2 begin */
    const tabs = ref<any>([
      {label: '角色权限', id: 'role-authority'},
      {label: '角色用户', id: 'role-user'},
    ])

    // role-authority | role-user
    const activeTab = ref('role-authority')

    const tabClick = (name: string) => {
      if(name === 'role-user'){
        searchRoleUser()
      }else{
        getRoleList()
      }
    }

    // 角色用户表格列
    const roleUserFields = ref<any[]>([
      {
        // 图标、名称、类型
        key: 'name',
        tableSlot: 'name',
        label: '姓名',
        minWidth: '120px',
        search: true,
        show: true
      },
      {

        key: 'username',

        label: '用户名',
        search: false,
        show: true
      },
      {

        key: 'nickname',

        label: '昵称',
        search: false,
        show: true
      },
      {

        key: 'sex',

        label: '性别',
        search: false,
        show: true
      },
      {

        key: 'phone',
        label: '联系电话',
        search: false,
        show: true
      },
      {

        key: 'email',
        label: '邮箱',
        search: false,
        show: true
      },
      {
        key: 'departments',
        label: '部门',
        search: false,
        tableSlot: 'departments',
        show: true
      },
      {

        key: 'posts',
        label: '岗位',
        tableSlot: 'posts',
        search: false,
        show: true
      },
      {

        key: 'operation',
        value: '',
        label: '操作',
        width: '100px',
        tableSlot: 'operation',
        search: false,
        show: true
      },
    ])
    // 查询条件
    const userSearchData = ref<any>({
      page: 1,
      rows: 15
    })

    const roleUserTotal = ref<number>(0)

    // 角色用户数据
    const roleUserData = ref<any[]>([])
    // 查询
    const searchRoleUser = async () => {
      const params = {
        roleId: selectId.value?.id,
        ...userSearchData.value
      }

      if(!params.roleId){
        return
      }

      const res = await roleUserApi.select(params)
      if(!res.success){
        console.error(res.msg)
        return
      }
      roleUserData.value = res.data
      roleUserTotal.value = res.total

    }

    /** 绑定人员 begin */
    // 人员选择状态
    const { baseUrl } = useHttpUrl()
    const token = useToken()
    const pickerState = reactive({
      visible: false,
      data: [],
      userList: []
    })
    // 人员选择方法
    const pickerMethods = {
      open: () => {
        pickerState.data = []
        pickerState.visible = true
      },
      handleOk: async (data: any) => {
        console.log('handleOk data ', data)
        const params = {
          roleId: selectId.value?.id,
          userIds: data.list?.map((item: any) => item.elementId) ?? []
        }
        const res = await roleUserApi.add(params)
        if(!res.success){
          msgWarning(res.msg)
          return
        }
        msgSuccess(res.msg)
        searchRoleUser()
      }
    }
    /** 绑定人员 end */
    /** v2 end */
    watch(
      () => visible.value,
      vis => {
        !vis && (editData.value = null)
      }
    )
    watch(
      () => selectId.value,
      vis => {
        if (vis)
          selectIdName.value = vis.name || ''
      }
    )
    // const filterRole = () => {
    //   roleLists.value.filter(role => role.name === searchText.value)
    // }

    // 获取权限
    const getRoleList = async () => {
      loading.value = true
      const { success, data, msg } = await roleApi.getRoleList()
      if (success) {
        const LIST = data.sort((a: any, b: any) => a.sortOrder! - b.sortOrder!)
        roleLists.value = _.cloneDeep(LIST)
        // recordList = _.cloneDeep(LIST)
        __roleLists.value = _.cloneDeep(LIST)
        selectId.value = data.length > 0 ? data?.[0] : null
      }
      else {
        msgWarning(msg)
      }
      loading.value = false
    }

    // 新增角色
    const handAddNewRole = () => {
      visible.value = true
    }
    //
    const removeRoleUser =async  (row: any) => {
      const params = {
        roleId: selectId.value?.id,
        userIds: [row.id]
      }
      const res = await roleUserApi.remove(params)
      if(!res.success){
        msgWarning(res.msg)
        return
      }
      msgSuccess(res.msg)
      searchRoleUser()
    }
    // 切换选中角色
    const handSelectRole = (role: RoleFormState) => {

      checkChange.value = false
      selectId.value = role

      if(activeTab.value === 'role-user'){
        searchRoleUser()
      }
    }
    // 编辑角色
    const handEditRole = (role: RoleFormState) => {
      visible.value = true
      editData.value = role
    }
    // 删除角色
    const handDeleteRole = async (role: RoleFormState) => {
      msgBoxWarnAsync(
        '删除角色',
        `删除后，角色【${role.name}】相关的用户将不能继续使用本角色菜单，无法恢复。确定删除吗？`,
        async () => {
          const { success, msg } = await roleApi.deleteRole(role.id)
          if (success) {
            msgSuccess(msg)
            getRoleList()
          }
          else {
            msgWarning(msg)
          }
        }
      )
    }

    const checkChange = ref(false)
    // 选项变化
    const handCheckChange = (bool: boolean) => {
      checkChange.value = bool
    }

    onMounted(() => {
      getRoleList()
    })
    // const searchRole = () => {
    //   if (searchText.value) {
    //     roleLists.value = roleLists.value.filter(
    //       item => item.name?.indexOf(searchText.value) !== -1
    //     )
    //   }
    //   else {
    //     roleLists.value = recordList
    //   }
    // }
    return () => (
      <>
        <IkSplitPan size={0} left-size={[0, 100]}>
          {{
            left: (
              <>
                <IkPageFull
                  header-title="角色列表"
                  refreshBtn={false}
                  settingBtn={false}
                  headerBorder={true}
                >
                  {{
                    headerRight: (
                      <>
                        <IkSvgIcon
                          show-bg
                          width={40}
                          pop
                          size="big"
                          title='刷新'
                          name="icon-shuaxin1"
                          onClick={() => getRoleList()}
                        />
                        <IkSvgIcon
                          v-role="ADD-ROLE"
                          onClick={() => handAddNewRole()}
                          show-bg
                          title='新增'
                          pop
                          size="big"
                          width={40}
                          font-size={40}
                          name="icon-xinzeng"
                        />
                      </>
                    ),
                    table: (
                      <>
                        <IkItemList
                            list={roleLists.value as any}
                            onSelect={(role: any) => handSelectRole(role)}
                            proxy={{ label: 'name', value: 'id' }}
                            confirmLeave={checkChange.value}
                            confirmLeaveText="当前角色配置未保存，是否确定切换？"
                          >
                            {{
                              suffix: ({ item }: { item: any; }) => (
                                <span class="flex">
                                  <IkSvgIcon title="编辑" pop show-bg width={28} v-role="UPDATE-ROLE" name="iksvg_bianji" onClick={withModifiers(
                                    () => handEditRole(item),
                                    ['stop']
                                  )} />
                                  <IkSvgIcon title="删除" pop show-bg width={28} type="warning" v-role="DELETE-ROLE" name="iksvg_shanchu" onClick={withModifiers(
                                    () => handDeleteRole(item),
                                    ['stop']
                                  )} />
                                </span>
                              )
                            }}
                          </IkItemList>
                      </>
                    )
                  }}
                </IkPageFull>
              </>
            ),
            right: (
              <>
              {selectId.value ?  <div class="current-info">
                <div class="current-info-title">
                  <span>{selectId.value?.name}</span>
                </div>
                <div>
                  <span class="current-info-icon">
                  <IkSvgIcon
                    title='数据权限'
                    name="iksvg_mima"
                    pop
                  />
                  </span>
                  <span class="current-info-text">
                    {selectId.value?.dataScopeTypeName ?? '--'}
                  </span>
                </div>
                <div>
                  <span class="current-info-icon">
                    <IkSvgIcon
                      title='描述'
                      name="iksvg_liebiao"
                      pop
                    />
                  </span>
                  <span class="current-info-text">
                    {selectId.value?.remark ?? '--'}
                  </span>
                </div>
              </div> : ''}
              <div class="tabs-box">
              <IkPageTabs v-model={activeTab.value} tabs={tabs.value} onTabClick={(e: any) => tabClick(e)}>
                {activeTab.value === 'role-authority' ? ( <IkPageFull
                    refreshBtn={false}
                    settingBtn={false}>
                    {{
                      headerRight: (
                        <>
                        {/* <span class="title">
                          {selectId.value?.name
                        ? `${selectId.value?.name} [数据权限：${selectId.value?.dataScopeTypeName}]`
                        : ''}
                        </span> */}
                        <IkSvgIcon
                          v-show={selectId.value?.name}
                          v-role="UPDATE-ROLE-MENU"
                          onClick={() => (helpState.value = !helpState.value)}
                          show-bg
                          pop
                          size="big"
                          title='保存配置'
                          name="iksvg_guidang"
                        />
                        </>

                      ),
                      table: <RoleListComfig
                          onCheckChange={bool => handCheckChange(bool) }
                          role={selectId.value!}
                          ref={refRole as any}
                          helpState={helpState.value}
                          check={checkChange.value}
                        />

                    }}
                  </IkPageFull>)
                  : (
                    <>
                      <IkPageFull
                        v-model={userSearchData.value}
                        refreshBtn={true}
                        fields={roleUserFields.value}
                        table-data={roleUserData.value}
                        total={roleUserTotal.value}
                        search={searchRoleUser}
                        settingBtn={true}>

                        {{
                          headerRight: (
                            <>
                            {/* <span class="title">
                              {selectId.value?.name
                            ? `${selectId.value?.name} [数据权限：${selectId.value?.dataScopeTypeName}]`
                            : ''}
                            </span> */}
                            <IkSvgIcon
                              v-show={selectId.value?.name}
                              v-role="UPDATE-ROLE-MENU"
                              onClick={() => pickerMethods.open()}
                              show-bg
                              pop
                              size="big"
                              title='保存配置'
                              name="iksvg_yonghu1"
                            />

                            </>
                          ),
                            name: ({data}: any) =>  <IkSideText
                            avatar={data.row.avatar}
                            name={data.row.name}
                            text={data.row.name}

                          ></IkSideText>,
                          departments: ({data}: any) => <span>{ikArray.listToString(data?.row.departments, 'deptName', ',')}</span>,
                          posts: ({data}: any) => <span>{ikArray.listToString(data?.row.posts, 'postName', ',')}</span>,
                          operation: ({data}: any) => <IkBtnContent num={1}>



                            <ElPopconfirm title="确定移除吗？" onConfirm={() => removeRoleUser(data.row)}>
                              {{
                                reference: <IkSvgIcon
                                name="iksvg_shanchu1"
                                show-bg
                                size="small"
                              />
                              }}
                            </ElPopconfirm>

                        </IkBtnContent>

                        }}
                      </IkPageFull>
                      <IkingPicker
                        ref="testRef"
                        v-model={pickerState.data}
                        v-model:show={pickerState.visible}
                        multiple={true}
                        children={true}
                        choose-type={['user']}
                        type-option={{ dep: 'DEPT', user: 'USER', role: 'ROLE', post: 'POST' }}
                        orgPid=""
                        prop-option={{
                          name: 'elementName',
                          id: 'elementId',
                          type: 'elementType',
                        }}
                        api={{
                          methods: 'post',
                          url: `${baseUrl}/server/component/pick/mix`,
                          headers: {
                            'Content-Type': 'application/json;charset=UTF-8',
                            'Authorization': token,
                          },
                        }}
                        onOk={(e: any) => pickerMethods.handleOk(e)}
                        emptyText="暂无数据" />
                  </>

                  )
                }

              </IkPageTabs>
              </div>


              </>
            )
          }}
        </IkSplitPan>
        <RoleModal
          v-model:visible={visible.value}
          editData={editData.value}
          onDataChange={() => getRoleList()}
        />
      </>
    )
  }
})

export default roleManage
